/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.image;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.lcdui.Image;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * 
 * @author kentelt
 * 
 */
public class ImageStore {

	public class ImageStoreException extends IllegalArgumentException {
		String msg;

		public ImageStoreException(String message) {
			msg = message;
		}

		public String getMessage() {
			return msg;
		}

		public String toString() {
			return msg;
		}

	}

	private RecordStore imgStore = null;

	public ImageStore() {

	}

	private boolean addRecord(byte[] imageData) {
		try {
			imgStore.addRecord(imageData, 0, imageData.length);
			return true;
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
			return false;
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
			return false;
		} catch (RecordStoreException e) {
			e.printStackTrace();
			return false;
		}
		// simple value to check if the value is added
		// return 911;
	}

	public void clearImageStore() {

	}

	private void closeImageStore() {
		try {
			imgStore.closeRecordStore();
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}

	}

	public int getRecordCount() {
		return 0;
	}

	public Image loadImage(String imageName) throws ImageStoreException {
		Image retImage = null;
		if (imageName == null) {
			throw new ImageStoreException("Image name cannot be null");
		} else {
			openImageStore();
			try {
				RecordEnumeration recEnum = imgStore.enumerateRecords(null, null, true);
				int total = recEnum.numRecords();
				for (int i = 0; i < total; i++) {
					try {
						int nextRecordID = recEnum.nextRecordId();
						// try {/
						byte[] rec = imgStore.getRecord(nextRecordID);
						ByteArrayInputStream bins = new ByteArrayInputStream(rec);
						DataInputStream dins = new DataInputStream(bins);
						String name = dins.readUTF();
						if (!name.equals(imageName))
							continue;
						int width = dins.readInt();
						int height = dins.readInt();
						// long timestamp = dins.readLong();
						int length = dins.readInt();
						int[] rawImg = new int[width * height];
						for (int j = 0; j < length; j++) {
							rawImg[j] = dins.readInt();
						}
						retImage = Image.createRGBImage(rawImg, width, height, false);
						dins.close();
						bins.close();
					} catch (InvalidRecordIDException e) {
						e.printStackTrace();
					} catch (RecordStoreException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} catch (RecordStoreNotOpenException e) {
				e.printStackTrace();
			} finally {
				closeImageStore();
			}
		}

		return retImage;
	}

	private void openImageStore() {
		try {
			imgStore = RecordStore.openRecordStore("MLB_STORE", true);
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}
	}

	public boolean saveImage(String name, Image image, boolean replaceExisting) throws ImageStoreException {
		boolean isSuccess = false;
		if (name == null) {
			throw new ImageStoreException("Image name cannot be null.please provide a name");
		} else if (image == null) {
			throw new ImageStoreException("Image cannot be null");
		} else {
			openImageStore();
			int width = image.getWidth();
			int height = image.getHeight();
			int[] imageRGBData = new int[width * height];
			// try {
			image.getRGB(imageRGBData, 0, width, 0, 0, width, height);
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream dout = new DataOutputStream(bout);
			try {
				dout.writeUTF(name);
				dout.writeInt(width);
				dout.writeInt(height);
				// dout.writeLong(System.currentTimeMillis());
				dout.writeInt(imageRGBData.length);
				for (int i = 0; i < imageRGBData.length; i++) {
					dout.writeInt(imageRGBData[i]);
				}
				dout.flush();
				dout.close();
				byte[] imgData = bout.toByteArray();
				if (!replaceExisting) {
					isSuccess = addRecord(imgData);
				} else { // if we need to replace existing image get the record
					// id first
				}
				dout.close();
				bout.close();

			} catch (IOException e) {
				e.printStackTrace();
				isSuccess = false;
			} finally {
				closeImageStore();
			}

		}
		return isSuccess;

	}
}
